"""
商品API路由
"""
from typing import Optional
from fastapi import APIRouter, Query, HTTPException, status
from pydantic import BaseModel, Field
from loguru import logger

from app.services.tools import search_product, get_available_coupons, get_price_history
from app.core.deps import get_db
from sqlalchemy.ext.asyncio import AsyncSession
from fastapi import Depends


router = APIRouter()


# ==================== Pydantic模型 ====================

class ProductSearchResponse(BaseModel):
    """商品搜索响应"""
    success: bool
    products: list
    total: int
    keyword: str


class CouponsResponse(BaseModel):
    """优惠券响应"""
    success: bool
    coupons: list
    total: int


# ==================== API路由 ====================

@router.get("/search", response_model=ProductSearchResponse)
async def search_products(
    keyword: str = Query(..., description="搜索关键词", min_length=1),
    category: Optional[str] = Query(None, description="商品分类"),
    limit: int = Query(10, ge=1, le=50, description="返回数量")
):
    """
    搜索商品
    
    根据关键词搜索商品信息
    """
    try:
        logger.info(f"搜索商品 | 关键词: {keyword} | 分类: {category}")
        
        products = await search_product(
            keyword=keyword,
            category=category,
            limit=limit
        )
        
        return ProductSearchResponse(
            success=True,
            products=products,
            total=len(products),
            keyword=keyword
        )
        
    except Exception as e:
        logger.error(f"搜索商品失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"系统错误: {str(e)}"
        )


@router.get("/coupons/{user_id}", response_model=CouponsResponse)
async def get_coupons(
    user_id: int
):
    """
    获取用户可用优惠券
    """
    try:
        logger.info(f"获取优惠券 | 用户: {user_id}")
        
        coupons = await get_available_coupons(user_id=user_id)
        
        return CouponsResponse(
            success=True,
            coupons=coupons,
            total=len(coupons)
        )
        
    except Exception as e:
        logger.error(f"获取优惠券失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"系统错误: {str(e)}"
        )


@router.get("/price-history")
async def get_product_price_history(
    product_id: Optional[int] = Query(None, description="商品ID"),
    product_sn: Optional[str] = Query(None, description="商品编号"),
    days: int = Query(30, ge=1, le=365, description="查询天数，默认30天"),
    db: AsyncSession = Depends(get_db)
):
    """
    查询商品价格历史
    
    支持按商品ID或商品编号查询
    """
    try:
        if not product_id and not product_sn:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="请提供商品ID或商品编号"
            )
        
        logger.info(f"查询价格历史 | ID: {product_id} | SN: {product_sn} | 天数: {days}")
        
        result = await get_price_history(
            product_id=product_id,
            product_sn=product_sn,
            days=days,
            db=db
        )
        
        if not result:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="未找到商品或价格历史数据"
            )
        
        return {
            "success": True,
            **result
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"查询价格历史失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"系统错误: {str(e)}"
        )

